package me.wsj.fengyun.ui.activity.web.web;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Build;
import android.util.AttributeSet;
import android.view.View;
import android.webkit.JsPromptResult;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ZoomButtonsController;

import java.lang.reflect.Field;

/**
 * TBS webview 加载Html
 */

public class MWebView extends WebView {

    public final String OLD_BASE_INTERFACE_NAME = "AppInterface";

    private boolean mScrollBar = false;
    private OnPageFinishedListener mPageFinishedListener = null;
    private OnPageStartedListener mPageStartedListener = null;
    private OnLoadPageListener mOnLoadPageListener = null;
    private OnReceivedErrorListener mReceivedErrorListener = null;
    private MAppInterface mAppInterface;


    public interface OnPageFinishedListener {
        void pageFinished(WebView v);//结束装载页面时调用
    }

    public interface OnReceivedErrorListener {
        void receivedError(WebView view, int errorCode, String description);
    }

    //add by yfren
    public interface OnLoadPageListener {
        void pageStarted(WebView v, String url);

        void pageFinished(WebView v, String url);//结束装载页面时调用
    }

    /**
     * 页面加载时调用
     */
    public interface OnPageStartedListener {
        void pageStarted(WebView v);
    }

    /**
     * add by wrnie
     * 如果需要调用setTitle和setToolbarVisibility的基础接口时，需要activity或fragment
     * 实现innerInterface接口，在该业务模块内进行设置头部和头部是否显示
     */
    public interface NativeViewListener {
        void setSelfTitle(String text);

        void setSelfToolbarVisibility(int status);
    }

    public void setOnPageFinishedListener(OnPageFinishedListener pageStartedListener) {
        mPageFinishedListener = pageStartedListener;
    }

    public void setOnReceivedErrorListener(OnReceivedErrorListener receivedErrorListener) {

        mReceivedErrorListener = receivedErrorListener;
    }

    public void setOnLoadPageListener(OnLoadPageListener onLoadPageListener) {
        mOnLoadPageListener = onLoadPageListener;
    }

    public void setOnPageStartedListener(OnPageStartedListener pageStartedListener) {
        mPageStartedListener = pageStartedListener;
    }


    public MWebView(Context context) {
        super(context);
        loadParams(context);
    }

    public MWebView(Context context, AttributeSet attrs) {
        super(context, attrs);
        loadParams(context);
    }


    @SuppressLint({"SetJavaScriptEnabled", "JavascriptInterface"})
    private void loadParams(Context context) {
        WebSettings s = getSettings();
        if (null == s) {
            return;
        }
        //s.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        s.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        //s.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL);
        // 配置settings
        s.setJavaScriptEnabled(true);
        // mWebView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
        // settings.setBlockNetworkImage(true);
        // settings.setRenderPriority(WebSettings.RenderPriority.HIGH);
        // 配置滚动条
        s.setCacheMode(WebSettings.LOAD_DEFAULT);
        s.setJavaScriptEnabled(true);
        s.setDefaultTextEncodingName("utf-8");
        s.setJavaScriptCanOpenWindowsAutomatically(true);
        s.setPluginState(WebSettings.PluginState.ON);
        s.setUseWideViewPort(true);
        s.setLoadWithOverviewMode(true);
        /*********************localStorage*******************/
        s.setDomStorageEnabled(true);
        s.setAppCacheMaxSize(1024 * 1024 * 8);
        String appCachePath = getContext().getCacheDir().getAbsolutePath();
        s.setAppCachePath(appCachePath);
        s.setAppCacheEnabled(true);
        s.setAllowFileAccess(true);
        /****************************************************/
        s.setSavePassword(false);
        s.setSaveFormData(false);
        s.setBuiltInZoomControls(false);
        s.setJavaScriptEnabled(true);
        s.setJavaScriptCanOpenWindowsAutomatically(true);

        setLongClickable(false);
        setVerticalScrollBarEnabled(mScrollBar);
        setScrollBarStyle(SCROLLBARS_INSIDE_OVERLAY);
        setZoomControlGone();
        //设置 WebViewClient
        setWebViewClient(mWvc);
        //设置 WebChromeClient，教师端未兼容知学宝拦截Url
        setWebChromeClient(mWvcc);
        //setInitialScale(100);
        //默认添加新的基础方法
        mAppInterface = new MAppInterface(context, this);
        addJavascriptInterface(mAppInterface, OLD_BASE_INTERFACE_NAME);
    }


    @Override
    public void setVerticalScrollBarEnabled(boolean hasBar) {
        mScrollBar = hasBar;
    }


    /**
     * 去除缩放控件
     */
    public void setZoomControlGone() {
        if (Integer.parseInt(Build.VERSION.SDK) >= 11) {
            this.getSettings().setDisplayZoomControls(false);
        } else {
            try {
                Class classType = WebView.class;
                Field field = classType.getDeclaredField("mZoomButtonsController");
                field.setAccessible(true);
                ZoomButtonsController mZoomButtonsController = new ZoomButtonsController(
                        this);
                mZoomButtonsController.getZoomControls().setVisibility(
                        View.GONE);
                try {
                    field.set(this, mZoomButtonsController);
                } catch (IllegalArgumentException | IllegalAccessException e) {
                    e.printStackTrace();
                }
            } catch (SecurityException | NoSuchFieldException e) {
                e.printStackTrace();
            }
        }
    }


    WebViewClient mWvc = new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            // 使用自己的WebView组件来响应Url加载事件
            loadUrl(url);
            return true;
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            //Log.d("WebViewClient", "onPageStarted");
            view.setBackgroundColor(Color.TRANSPARENT);
            if (mPageStartedListener != null) {
                mPageStartedListener.pageStarted(view);
            }
            if (null != mOnLoadPageListener) {
                mOnLoadPageListener.pageStarted(view, url);
            }
            super.onPageStarted(view, url, favicon);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            if (mPageFinishedListener != null) {
                mPageFinishedListener.pageFinished(view);
            }
            if (null != mOnLoadPageListener) {
                mOnLoadPageListener.pageFinished(view, url);
            }
            super.onPageFinished(view, url);
        }

        @Override
        public void onLoadResource(WebView view, String url) {
            super.onLoadResource(view, url);
        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            if (mReceivedErrorListener != null) {
                mReceivedErrorListener.receivedError(view, errorCode, description);
            }
            super.onReceivedError(view, errorCode, description, failingUrl);
        }
    };


    WebChromeClient mWvcc = new WebChromeClient() {

        // 处理Alert事件
        @Override
        public boolean onJsAlert(WebView view, String url, String message, final JsResult result) {
            // 显示网页中的alert对话框
            //AlertInstance.getAlertInstance(getContext()).showAlert("提示", message, result, null)
            return false;
        }

        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
        }

        // 处理Confirm事件
        @Override
        public boolean onJsConfirm(WebView view, String url, String message, final JsResult result) {
            return true;
        }

        // 处理提示事件
        @Override
        public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, JsPromptResult result) {
            return super.onJsPrompt(view, url, message, defaultValue, result);
        }
    };
}
